<?php

namespace App\Models;

use App\Http\Library\BaiduMap;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\Money
 *
 * @property int $id
 * @property string $price 充值金额
 * @property string $give_price 赠送金额
 * @property int $sort 排序
 * @property array|null $options 其他规则
 * @property int $status 状态:0=正常,1=隐藏
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|Money newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Money newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Money query()
 * @method static \Illuminate\Database\Eloquent\Builder|Money whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Money whereGivePrice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Money whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Money whereOptions($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Money wherePrice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Money whereSort($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Money whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Money whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class Money extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'moneys';

    protected $casts = ['options'=>'json'];

    protected static function booted()
    {
        self::saving(function (Money $money){
            $rule = request()->input("rule");
            $money->options = json_decode($rule,true);
        });
    }

    public static function getData(){
        $longitude = request()->input("longitude","");
        $latitude = request()->input("latitude","");
        $list = self::query()->where("status",0)->orderByDesc("sort")->orderByDesc("id")->get();
        if ($longitude&&$latitude){
            $area_id = Area::findAddress($longitude,$latitude);
            if ($area_id){
                foreach ($list as $item){
                    self::getGivePrice($area_id, $item);
                }
            }
        }
        $rules = \App\Api\Models\Config::getName("money_rules");
        return [
          'items'=>$list,
          'rules'=>json_decode($rules,true)
        ];
    }

    public static function getGivePrice($area_id, &$item){
        $options = $item->options;
        if ($options){
            foreach ($options as $option){
                if (in_array($area_id,$option['city'])){
                    $item->give_price = number_format($option['price'],2);
                    break;
                }
            }
        }
        unset($item->options);
    }

}
